package process

import (
	ss "dmsv/session"
	"github.com/beego/beego/v2/core/logs"
)

const max_chan_len = 100000

//预测外呼
func AddGuessCallNumber(taskId, companyId string, numbers []string) bool {
	c, ok := gEterpriceHandle[companyId]
	if ok {

		numberChan, ok := c.guesCalltask.Load(taskId)
		if ok {
			go func() {
				for _, n := range numbers {
					if len(numberChan.(chan string)) < max_chan_len {
						numberChan.(chan string) <- n
					} else {
						break
					}
				}
			}()
		} else {
			logs.Error("task Id %v is not found", taskId)
			return false
		}

	} else {
		logs.Error("company Id%v is not found", companyId)
		return false
	}

	return true
}

//预测外呼
func CreateGuessCallTask(taskId, companyId string, speed int) bool {
	c, ok := gEterpriceHandle[companyId]
	if ok {
		callNumberChan := make(chan string, max_chan_len)

		c.guesCalltask.Store(taskId, callNumberChan)

		//sCallChan := make(chan *ss.SessionInfo, len(c.service)*4)

		//创建外呼坐席任务

		//创建外呼任务

	} else {
		logs.Error("company Id%v is not found", companyId)
		return false
	}

	return true
}

func (c *Company) outCallUserProcess(sCalls chan *ss.SessionInfo, event chan *ss.CallBackData) {

	for {

		ev, ok := <-event
		if !ok {

			return
		}

		// 不是用户消息,为异常
		if ev.Dir != ss.LEG_DIR_USER {
			logs.Error("receiv wrong message :%v", ev)
			continue
		}

		switch ev.Event {
		case ss.CALL_EVENT_ANSWER:

		case ss.CALL_EVENT_HANGUP:
			rs := errCode{}

			hangUp := ev.Data.(*ss.HangInfo)

			switch hangUp.Dir {
			case ss.HANG_UP_LINEERR:
				rs = errCalleeLineErr
			case ss.HANG_UP_REFUSE:
				rs = errCalleeRefuse
			default:
				//未接听
				rs = errCalleeUnAnswer
			}
			logs.Debug("[%v] call:%v", rs)
		}
	}
}

func (c *Company) outCallServiceProcess(finishChan chan string, sCalls chan *ss.SessionInfo, event chan *ss.CallBackData) {

	for {

		ev, ok := <-event
		if !ok {

			return
		}

		switch ev.Event {
		case ss.CALL_EVENT_ANSWER:
			if ev.Dir == ss.LEG_DIR_SERVICE {
				sCalls <- ev.Ssion
			} else {
				logs.Error("wrong message...:%v", ev)
			}

		case ss.CALL_EVENT_HANGUP:
			rs := errCode{}
			if ev.Dir == ss.LEG_DIR_USER {
				hangUp := ev.Data.(*ss.HangInfo)
				//话单
				if hangUp.Duration > 0 {
					if ss.HANG_UP_USER == hangUp.Dir {
						rs = errCalleeHangup
					} else {
						rs = errCallerHangup
					}
				} else {
					switch hangUp.Dir {
					case ss.HANG_UP_LINEERR:
						rs = errCalleeLineErr
					case ss.HANG_UP_REFUSE:
						rs = errCalleeRefuse
					default:
						//未接听
						rs = errCalleeUnAnswer
					}
				}

			} else {

			}
			logs.Debug("[%v] :%v", ev.Ssion.GetSessionId(), rs)
		}
	}
}
